package com.fanrui.code.chess;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.RandomUtils;

import com.fanrui.code.chess.mahjong.CanHostingGamer;
import com.fanrui.code.chess.mahjong.MahjongGamer;
import com.fanrui.code.chess.mahjong.MahjongRobot;
import com.fanrui.code.threadgroup.GroupDeterminer;

public class ChessGamerManager {

	private ChessGamerManager() {}
	
	private static class ChessGamerManagerSingleton {
		private static ChessGamerManager instance = new ChessGamerManager();
	}
	
	public static ChessGamerManager getInstance() {
		return ChessGamerManagerSingleton.instance;
	}
	
	private AtomicInteger idCreater = new AtomicInteger(0);
	
	/**
	 * 用户ID和玩家映射表
	 */
	private ConcurrentMap<Long, IChessGamer<?>> gamers = new ConcurrentHashMap<Long, IChessGamer<?>>();
	
	private AtomicInteger ropbotIdCreater = new AtomicInteger(0);
	
	public void trick(GroupDeterminer<Long> group, int detlaTime) {
		Collection<IChessGamer<?>> findAll = gamers.values();
		for (IChessGamer<?> gamer : findAll) {
			if (!group.isInGroup(Math.abs(gamer.getPlayerID()))) {
				continue;
			}
			// 注意detlaTime的使用，如果在服务器卡的情况下可能会导致延迟
			gamer.trick();
		}
	}

	public IChessGamer<?> findGamer(Long playerID) {
		if(playerID == null){
			return null;
		}else{
			return gamers.get(playerID);
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T extends IChessGamer<?>> T findGamer(long playerID,Class<T> clazz) {
		return (T) gamers.get(playerID);
	}

	@SuppressWarnings("unchecked")
	public <T extends IChessGamer<?>> T create( long playerID, int tableID, Class<T> calzz, String ip, double x, double y) {
		T result = (T) new CanHostingGamer(idCreater.incrementAndGet(), playerID, tableID, ip, x, y);
		gamers.putIfAbsent(result.getPlayerID(), result);
		return result;
	}

	public void remove(IChessGamer<?> gamer) {
		gamers.remove(gamer.getPlayerID());
	}

	/**
	 * 创建一个麻将机器人
	 * 
	 * @param playerId
	 * @param table
	 * @param seatNO
	 * @return MahjongGamer
	 */
	public MahjongGamer createRobotGamer(int tableId,int enterGold,int leaveGold) {
		MahjongGamer gamer = new MahjongRobot(idCreater.incrementAndGet(),ropbotIdCreater.addAndGet(1), tableId);
		gamer.getPlayerInfo().setGold(RandomUtils.nextInt(enterGold, leaveGold));
		gamers.put(gamer.getPlayerID(), gamer);
		return gamer;
	}
}
